package com.free.instadownload.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;

public class Utils {

	// Loc link Poster cua Media tu link Share Instagram
	public static String getLinkPoster(String linkShare) {
		String linkPoster = "";
		try {
			Document doc = Jsoup.connect(linkShare).get();
			Element linkPosterE = doc.select("meta[property=og:image]").first();
			linkPoster = linkPosterE.attr("content");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return linkPoster;
	}

	// Lay anh tu URL
	public static Drawable getImageFromURL(String url) {
		URL link = null;
		Drawable dr = null;
		try {
			link = new URL(url);
			InputStream is = (InputStream) link.getContent();
			dr = Drawable.createFromStream(is, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dr;
	}

	// Chuyển một input stream thành một chuỗi string
	public static String streamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String response = "";
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				response += line;
			}
			reader.close();
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return response;
	}

	//
	// // Lay access_token
	// private String getAccessToken(String code) {
	// try {
	// URL url = new URL("https://api.instagram.com/oauth/access_token");
	// HttpURLConnection httpURLconnection = (HttpURLConnection) url
	// .openConnection();
	// httpURLconnection.setRequestMethod("POST");
	// httpURLconnection.setDoInput(true);
	// httpURLconnection.setDoOutput(true);
	// OutputStreamWriter writer = new OutputStreamWriter(
	// httpURLconnection.getOutputStream());
	// String params = "client_id=" + Constants.CLIENT_ID
	// + "&client_secret=" + Constants.CLIENT_SECRET
	// + "&grant_type=authorization_code" + "&redirect_uri="
	// + Constants.REDIRECT_URI + "&code=" + code;
	// writer.write(params);
	// writer.flush();
	//
	// String response = streamToString(httpURLconnection.getInputStream());
	// httpURLconnection.disconnect();
	// Log.d("RESPONSE", response);
	// return response;
	// } catch (MalformedURLException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// return null;
	// }

	// Lay media_id tu link share
	public static String getMediaID(String linkShare) {
		String media_id = "";
		try {
			URL url = new URL(Constants.OEMBED_URL + linkShare);
			String response = streamToString((InputStream) url.getContent());
			JSONObject object = (JSONObject) new JSONTokener(response)
					.nextValue();
			media_id = object.getString("media_id");
			if (media_id != null)
				return media_id;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	// Lay kieu Media tu media_id
	public static String getTypeMedia(String mediaID) {
		String type = "";
		try {
			URL url = new URL("https://api.instagram.com/v1/media/" + mediaID
					+ "?access_token=" + Constants.ACCESS_TOKEN);
			String response = streamToString((InputStream) url.getContent());
			JSONObject object = (JSONObject) new JSONTokener(response)
					.nextValue();
			JSONObject oj = object.getJSONObject("data");
			type = oj.getString("type");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return type;
	}

	// Lay link chua image voi kich thuoc low_resolution(306), thumbnail(150),
	// standard_resolution(612)
	// va video voi kich thuoc low_bandwidth, low_resolution,
	// standard_resolution
	public static HashMap<String, String> getLinkMedia(String mediaID,
			String type) {
		HashMap<String, String> links = new HashMap<String, String>();
		String lowResolution = "";
		String thumbnail = "";
		String standardRsolution = "";
		if (type.equals("image")) {
			try {
				URL url = new URL("https://api.instagram.com/v1/media/"
						+ mediaID + "?access_token=" + Constants.ACCESS_TOKEN);
				String response = streamToString((InputStream) url.getContent());
				JSONObject object = (JSONObject) new JSONTokener(response)
						.nextValue();
				JSONObject oj1 = object.getJSONObject("data");
				JSONObject oj2 = oj1.getJSONObject("images");

				lowResolution = oj2.getJSONObject("low_resolution").getString(
						"url");
				thumbnail = oj2.getJSONObject("thumbnail").getString("url");
				standardRsolution = oj2.getJSONObject("standard_resolution")
						.getString("url");
				links.put("low_resolution", lowResolution);
				links.put("thumbnail", thumbnail);
				links.put("standard_resolution", standardRsolution);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				URL url = new URL("https://api.instagram.com/v1/media/"
						+ mediaID + "?access_token=" + Constants.ACCESS_TOKEN);
				String response = streamToString((InputStream) url.getContent());
				JSONObject object = (JSONObject) new JSONTokener(response)
						.nextValue();
				JSONObject oj1 = object.getJSONObject("data");
				JSONObject oj2 = oj1.getJSONObject("videos");
				lowResolution = oj2.getJSONObject("low_bandwidth").getString(
						"url");
				thumbnail = oj2.getJSONObject("low_resolution")
						.getString("url");
				standardRsolution = oj2.getJSONObject("standard_resolution")
						.getString("url");
				links.put("low_bandwidth", lowResolution);
				links.put("low_resolution", thumbnail);
				links.put("standard_resolution", standardRsolution);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return links;
	}

	// Lay du lieu tu clipboard
	@SuppressLint("NewApi")
	public static String readFromClipboard(Context context) {
		int sdk = android.os.Build.VERSION.SDK_INT;
		if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
			ClipboardManager clipboard = (ClipboardManager) context
					.getSystemService(Context.CLIPBOARD_SERVICE);
			return clipboard.getText().toString();
		} else {
			ClipboardManager clipboard = (ClipboardManager) context
					.getSystemService(context.CLIPBOARD_SERVICE);

			// Gets a content resolver instance
			ContentResolver cr = context.getContentResolver();

			// Gets the clipboard data from the clipboard
			ClipData clip = clipboard.getPrimaryClip();
			if (clip != null) {

				String text = null;

				// Gets the first item from the clipboard data
				ClipData.Item item = clip.getItemAt(0);

				// Tries to get the item's contents as a URI pointing to a note
				Uri uri = item.getUri();

				// If the contents of the clipboard wasn't a reference to a
				// note, then
				// this converts whatever it is to text.
				if (text == null) {
					text = coerceToText(context, item).toString();
				}

				return text;
			}
		}
		return "";
	}

	@SuppressLint("NewApi")
	public static CharSequence coerceToText(Context context, ClipData.Item item) {
		// If this Item has an explicit textual value, simply return that.
		CharSequence text = item.getText();
		if (text != null) {
			return text;
		}

		// If this Item has a URI value, try using that.
		Uri uri = item.getUri();
		if (uri != null) {

			// First see if the URI can be opened as a plain text stream
			// (of any sub-type). If so, this is the best textual
			// representation for it.
			FileInputStream stream = null;
			try {
				// Ask for a stream of the desired type.
				AssetFileDescriptor descr = context.getContentResolver()
						.openTypedAssetFileDescriptor(uri, "text/*", null);
				stream = descr.createInputStream();
				InputStreamReader reader = new InputStreamReader(stream,
						"UTF-8");

				// Got it... copy the stream into a local string and return it.
				StringBuilder builder = new StringBuilder(128);
				char[] buffer = new char[8192];
				int len;
				while ((len = reader.read(buffer)) > 0) {
					builder.append(buffer, 0, len);
				}
				return builder.toString();

			} catch (FileNotFoundException e) {
				// Unable to open content URI as text... not really an
				// error, just something to ignore.

			} catch (IOException e) {
				// Something bad has happened.
				Log.w("ClippedData", "Failure loading text", e);
				return e.toString();

			} finally {
				if (stream != null) {
					try {
						stream.close();
					} catch (IOException e) {
					}
				}
			}

			// If we couldn't open the URI as a stream, then the URI itself
			// probably serves fairly well as a textual representation.
			return uri.toString();
		}

		// Finally, if all we have is an Intent, then we can just turn that
		// into text. Not the most user-friendly thing, but it's something.
		Intent intent = item.getIntent();
		if (intent != null) {
			return intent.toUri(Intent.URI_INTENT_SCHEME);
		}

		// Shouldn't get here, but just in case...
		return "";
	}
}
